package com.ruoyi.asset.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.asset.utils.FJRequestUtils;
import com.ruoyi.asset.utils.SQRequestUtils;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.asset.mapper.GhAssetRecordMapper;
import com.ruoyi.asset.domain.GhAssetRecord;
import com.ruoyi.asset.service.IGhAssetRecordService;
import org.springframework.util.CollectionUtils;

/**
 * 评估记录Service业务层处理
 * 
 * @author Liu
 * @date 2025-06-23
 */
@Service
public class GhAssetRecordServiceImpl implements IGhAssetRecordService 
{
    @Autowired
    private GhAssetRecordMapper ghAssetRecordMapper;

    @Autowired
    private FJRequestUtils fjRequestUtils;

    @Autowired
    private SQRequestUtils sqRequestUtils;

    /**
     * 查询评估记录
     * 
     * @param id 评估记录主键
     * @return 评估记录
     */
    @Override
    public GhAssetRecord selectGhAssetRecordById(Long id) {
        GhAssetRecord ghAssetRecord = ghAssetRecordMapper.selectGhAssetRecordById(id);
        if (ghAssetRecord.getStatus() == 1 && !StringUtils.isEmpty(ghAssetRecord.getResponseText())) {
            return ghAssetRecord;
        }
        JSONObject detail = sqRequestUtils.findDetail(ghAssetRecord.getOrderNo());
        ghAssetRecord.setResponseText(detail.toString());
        return ghAssetRecord;
    }

    /**
     * 查询评估记录列表
     * 
     * @param ghAssetRecord 评估记录
     * @return 评估记录
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<GhAssetRecord> selectGhAssetRecordList(GhAssetRecord ghAssetRecord) {
        return ghAssetRecordMapper.selectGhAssetRecordList(ghAssetRecord);
    }

    /**
     * 新增评估记录
     * 
     * @param ghAssetRecord 评估记录
     * @return 结果
     */
    @Override
    public int insertGhAssetRecord(GhAssetRecord ghAssetRecord) {
        ghAssetRecord.setCreateTime(DateUtils.getNowDate());
        ghAssetRecord.setCreateBy(SecurityUtils.getUserId().toString());
        if (ghAssetRecord.getSourceType() == 0) {
            String asset = fjRequestUtils.asset(ghAssetRecord.getVin());
            JSONObject jsonObject = JSONUtil.parseObj(asset);
            ghAssetRecord.setPdfUrl(jsonObject.getStr("pdfUrl"));
            ghAssetRecord.setResponseText(asset);
            ghAssetRecord.setOrderNo(jsonObject.getStr("detectOrderNo"));
            ghAssetRecord.setPrice(jsonObject.getStr("detectPrice"));
            ghAssetRecord.setStatus(1);
         } else {
            ghAssetRecord.setOrderNo( submitToSq(ghAssetRecord));
            ghAssetRecord.setStatus(0);
        }
        return ghAssetRecordMapper.insertGhAssetRecord(ghAssetRecord);
    }

    private String submitToSq(GhAssetRecord ghAssetRecord) {
        JSONObject data = ghAssetRecord.getData();
        for (Object o : ghAssetRecord.getTempArr()) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            JSONArray items = jsonObject.getJSONArray("items");
            for (Object item : items) {
                JSONObject itemObj = JSONUtil.parseObj(item);
                String id = itemObj.getStr("id");
                Integer isMust = itemObj.getInt("isMust");
                String type = itemObj.getStr("type");
                if (isMust != null && 1 == isMust && data.get(id) == null) {
                    throw new SecurityException(itemObj.getStr("label") + "必填");
                }
                if (type.equals("file-image") && isMust != null && 1 == isMust && CollectionUtils.isEmpty(data.getJSONArray(id))) {
                    throw new SecurityException(itemObj.getStr("label") + "必填");
                }
                if (type.equals("file-image") && !CollectionUtils.isEmpty(data.getJSONArray(id))) {
                    data.set(id, JSONUtil.parseObj(data.getJSONArray(id).get(0)).getStr("url"));
                } else if (type.equals("file-image") && CollectionUtils.isEmpty(data.getJSONArray(id))) {
                    data.set(id, null);
                }
                if (itemObj.getStr("label").equals("VIN")) {
                    ghAssetRecord.setVin(data.getStr(id));
                }
            }
        }
        //选配参数照片
        JSONArray tempArr = ghAssetRecord.getTempArr();
        for (Object o : tempArr) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            String group = jsonObject.getStr("group");
            if (group.contains("参配信息")) {
                JSONArray items = jsonObject.getJSONArray("items");
                for (Object item : items) {
                    JSONObject itemObj = JSONUtil.parseObj(item);
                    String id = itemObj.getStr("id");
                    Integer anInt = data.getInt(id);
                    if (anInt > 0 && StringUtils.isEmpty(data.getStr(id + "Pic"))) {
                        throw new SecurityException(itemObj.getStr("label") + "照片必填");
                    }
                }
            }
            if (group.contains("上传任意一张")) {
                JSONArray items = jsonObject.getJSONArray("items");
                if (StringUtils.isEmpty(data.getStr(JSONUtil.parseObj(items.get(0)).getStr("id"))) &&
                        StringUtils.isEmpty(data.getStr(JSONUtil.parseObj(items.get(1)).getStr("id")))) {
                    throw new SecurityException("证件照片(上传任意一张)");
                }
            }
        }
//        data.remove("province");
        JSONObject address = new JSONObject();
        address.set("provinceCode",data.getStr("province"));
        address.set("cityCode",data.getStr("parkingLot"));
        address.set("provinceName", data.getStr("provinceName"));
        address.set("cityName", data.getStr("cityName"));
        data.set("parkingLot", address.toString());
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("templateId", ghAssetRecord.getCarTypeSub());
        jsonObject.set("createName", SecurityUtils.getLoginUser().getUser().getNickName());
        jsonObject.set("mobile", SecurityUtils.getLoginUser().getUser().getPhonenumber());
        jsonObject.set("values", data);
        if (!StringUtils.isEmpty(ghAssetRecord.getOrderNo())) {
            jsonObject.set("detectionId", ghAssetRecord.getOrderNo());
        }
        return sqRequestUtils.submit(jsonObject);
    }
    /**
     * 修改评估记录
     * 
     * @param ghAssetRecord 评估记录
     * @return 结果
     */
    @Override
    public int updateGhAssetRecord(GhAssetRecord ghAssetRecord)
    {
        ghAssetRecord.setUpdateTime(DateUtils.getNowDate());
        GhAssetRecord record = ghAssetRecordMapper.selectGhAssetRecordById(ghAssetRecord.getId());
        ghAssetRecord.setOrderNo(record.getOrderNo());
        String s = submitToSq(ghAssetRecord);
        ghAssetRecord.setStatus(0);
//        ghAssetRecord.setResponseText(null);
        return ghAssetRecordMapper.updateGhAssetRecord(ghAssetRecord);
    }

    /**
     * 批量删除评估记录
     * 
     * @param ids 需要删除的评估记录主键
     * @return 结果
     */
    @Override
    public int deleteGhAssetRecordByIds(Long[] ids)
    {
        return ghAssetRecordMapper.deleteGhAssetRecordByIds(ids);
    }

    /**
     * 删除评估记录信息
     * 
     * @param id 评估记录主键
     * @return 结果
     */
    @Override
    public int deleteGhAssetRecordById(Long id)
    {
        return ghAssetRecordMapper.deleteGhAssetRecordById(id);
    }

    @Override
    public void getSQDetail(Long id) {
        GhAssetRecord ghAssetRecord = ghAssetRecordMapper.selectGhAssetRecordById(id);
        if (ghAssetRecord.getSourceType() == 0 || ghAssetRecord.getStatus() != 0) return;
        String vin = ghAssetRecord.getVin();
        if (StringUtils.isEmpty(ghAssetRecord.getOrderNo())) {
            //获取detectionId
           String detectionId = sqRequestUtils.detections(vin);
           ghAssetRecord.setOrderNo(detectionId);
           ghAssetRecordMapper.updateGhAssetRecord(ghAssetRecord);
        }
        JSONObject detail = sqRequestUtils.findDetail(ghAssetRecord.getOrderNo());
        Integer detectionStatus = detail.getInt("detectionStatus");
        if (detectionStatus == 1) return;
        GhAssetRecord update = new GhAssetRecord();
        update.setId(id);
        if (detectionStatus == 2) {
            update.setStatus(1);
            update.setPdfUrl(detail.getStr("pdfUrl"));
            BigDecimal retailPrice = new BigDecimal(detail.getStr("purchasePrice")).multiply(new BigDecimal(10000));
            update.setPrice(retailPrice.toString());
        } else if (detectionStatus == 7) {
            update.setStatus(2);
            update.setRejectReason(detail.getStr("rejectReason"));
        }
        update.setResponseText(detail.toString());
        update.setResponseText(detail.toString());
        ghAssetRecordMapper.updateGhAssetRecord(update);
    }
}
